<?php
namespace api\modules\v1\forms;
use common\enums\AccountTypeEnum;
use common\models\member\MemberWithdraw;
use common\helpers\ArrayHelper;
use common\models\forms\CreditsLogForm;
use common\models\member\BankAccount;
use Yii;

class WithdrawForm extends MemberWithdraw
{   
    public $password;
    public $_member;
    public $account_id;
    /**
     * @return array
     */
    public function rules()
    {
        return ArrayHelper::merge(parent::rules(), [
            [['password', 'account_id', 'amount'], 'required'],
            ['amount', 'verifyAmount'],
            ['password','verifyPassword'],
            ['account_id','verifyAccount'],
        ]);
    }

    public function verifyPassword()
    {
        if (!$this->_member->validateSecurityPassword($this->password)) {
            throw new \Exception("支付密码不正确");
        }
    }

    public function verifyAmount()
    {
        $withdraw__min = Yii::$app->debris->backendConfig('withdraw__min');

        if ($this->amount < 0) {
            return $this->addError('amount', Yii::t('app', 'Error'));
        }

        if ($this->amount < $withdraw__min) {
            return $this->addError('amount',Yii::t('app','最低提取数量为'.$withdraw__min));
        }
        $fee = self::getCashFee() / 100;

        $this->fee = $this->amount * $fee;
        $this->money = $this->amount - $this->fee - $this->shuifei;
    }

    public function verifyAccount()
    {
        $account = BankAccount::find()->where(['id'=>$this->account_id,'member_id'=>$this->member_id])->one();
        if(!$account){
            return $this->addError('account_id',Yii::t('app','银行账户有误'));
        }
        if($account->account_type == AccountTypeEnum::UNION){
            $this->bank_user_name = $account->real_name;
        }
        $this->open_bank = '';
        $this->card_number = $account->account_number;
        $this->type = $account->account_type;
    }

    public function add()
    {
        Yii::$app->services->memberCreditsLog->decrMoney(new CreditsLogForm([
            'member' => $this->_member,
            'num' => $this->amount,
            'credit_group' => 'cash',
            'remark' => 'withdraw',
        ]));

        return $this->save();
    }
}
